using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using Microsoft.WowAddonStudio.FrameXml.Serialization;

using Color = Microsoft.WowAddonStudio.FrameXml.Serialization.Color;

namespace Microsoft.WowAddonStudio.FrameXml.Components.Editors
{
	/// <summary>
	/// Provides a System.Drawing.Design.UITypeEditor for visually picking a color.
	/// </summary>
	public class ShadowEditor : ColorEditor
	{
		/// <summary>
		/// Edits the given object value using the editor style provided by the <see cref="M:System.Drawing.Design.ColorEditor.GetEditStyle(System.ComponentModel.ITypeDescriptorContext)"/> method.
		/// </summary>
		/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that can be used to gain additional context information.</param>
		/// <param name="provider">An <see cref="T:System.IServiceProvider"/> through which editing services may be obtained.</param>
		/// <param name="value">An instance of the value being edited.</param>
		/// <returns>
		/// The new value of the object. If the value of the object has not changed, this should return the same object it was passed.
		/// </returns>
		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
		    var shadow = value != null ? ((Shadow) value).Copy() : new Shadow();

            // Get the color value before editing
            var color = shadow.Color != null ? (object)shadow.Color.ToColor() : null;

            // Edit the color of the shadow
            object newColor = base.EditValue(context, provider, color);

            // Check whether any edits were made by ColorEditor's EditValue
            if (color != newColor)
            {
                // Set the shadow's color based on the new value
                shadow.Color = newColor != null ? Color.FromColor((System.Drawing.Color)newColor) : null;

                // Return the same shadow
                return shadow;
            }

		    return value;
		}

		/// <summary>
		/// Paints a representative value of the given object to the provided canvas.
		/// </summary>
		/// <param name="e">What to paint and where to paint it.</param>
		public override void PaintValue(PaintValueEventArgs e)
		{
			base.PaintValue(e);

		    if ((e.Value is Shadow))
		    {
		        var color = ((Shadow) e.Value).Color;
		        if (color != null)
		        {
		            using (var brush = new SolidBrush(color.ToColor()))
		                e.Graphics.FillRectangle(brush, e.Bounds);
		        }
		    }
		}
	}
}